package net.studou.action;

import net.studou.bean.tools.BeanUtils;
import net.studou.bean.tools.Properties;
import net.studou.exception.ShopKeeperException;
import net.studou.exception.UserExistException;
import net.studou.exception.UserForbidException;
import net.studou.exception.UserNotExistException;
import net.studou.exception.VerifyCodeException;
import net.studou.po.User;
import net.studou.tools.STDLogger;
import net.studou.verify.CheckChain;
import net.studou.verify.CheckEquals;
import net.studou.verify.CheckFormat;
import net.studou.verify.CheckLength;
import net.studou.verify.CheckNoNull;
import net.studou.verify.CheckNull;
import net.studou.vo.VMessage;
import net.studou.vo.VUser;

import org.springframework.stereotype.Component;

@Component("userAction")
public class UserAction extends BasicAction {

	private static final long serialVersionUID = -7864662278384572216L;

	private STDLogger logger = STDLogger.getLogger(UserAction.class);

	public String register(){
		User pUser = new User();
		pUser.setIp(getRequest().getRemoteAddr());
		Properties properties = new Properties("userName, password, operateCode, tbUrl, shopKeeper, qq");
		properties.addPropertyMap("parentUserName", "parentUser.userName");
		BeanUtils.copyBean(getUser(), pUser, properties);

		String forward = null;
		
		try {
			getVerifyCodeService().verifyCode(getUser(), getSession());
			setUserToSession(getUserService().regsiter(pUser));
			forward = SUCCESS;
			setFeedBackMesssage(new VMessage(VMessage.SUCCESS, "注册成功", "您现在以 “" + pUser.getUserName() + "” 的身份登录超级土豆平台，祝您使用愉快！"));
		} catch (UserExistException e) {
			logger.debug(e);
			forward = INPUT;
			setFeedBackMesssage(new VMessage(VMessage.ERROR, "注册失败", "请认真检查注册信息是否正确。"));
			setFieldErrorMessage("userNameError", "该用户名已经被注册");
		} catch (ShopKeeperException e) {
			logger.debug(e);
			forward = INPUT;
			setFeedBackMesssage(new VMessage(VMessage.ERROR, "注册失败", "请认真检查注册信息是否正确。"));
			setFieldErrorMessage("shopKeeperError", "该掌柜名称与店铺的真实掌柜不相同");
		} catch (UserNotExistException e) {
			logger.debug(e);
			forward = INPUT;
			setFeedBackMesssage(new VMessage(VMessage.ERROR, "注册失败", "请认真检查注册信息是否正确。"));
			setFieldErrorMessage("parentUserNameError", "推荐人名称不存在，请核对");
		} catch (VerifyCodeException e) {
			logger.debug(e);
			forward = INPUT;
			setFeedBackMesssage(new VMessage(VMessage.ERROR, "注册失败", "请认真检查注册信息是否正确。"));
			setFieldErrorMessage("codeError", "验证码错误");
		}

		return forward;
	}

	public String userInfo() {
		User pUser = getUserFromSession("userName, lastLoginTime, lastLoginIP");
		
		String forward = null;

		try {
			setUserToSession(getUserService().getUserInfo(pUser));
			forward = SUCCESS;
		} catch (UserNotExistException e) {
			logger.debug(e);
			forward = INPUT;
			setFeedBackMesssage(new VMessage(VMessage.ERROR, "登录失败", "请认真检查登录信息是否正确。"));
			setFieldErrorMessage("userNameError", "用户名或密码不正确");
		} catch (UserForbidException e) {
			logger.debug(e);
			forward = SUCCESS;
			setUserToSession((User) e.getPo(), true);
		}
		return forward;
	}
	
	public String login() {
		User pUser = new User();
		pUser.setIp(getRequest().getRemoteAddr());
		BeanUtils.copyBean(getUser(), pUser, new Properties("userName, password"));

		String forward = null;

		try {
			// TODO 打开验证码功能
			getVerifyCodeService().verifyCode(getUser(), getSession());
			setUserToSession(getUserService().loginVerify(pUser));
			forward = SUCCESS;
			setFeedBackMesssage(new VMessage(VMessage.SUCCESS, "登录成功", "您现在以 “" + pUser.getUserName() + "” 的身份登录超级土豆平台，祝您使用愉快！"));
		} catch (UserNotExistException e) {
			logger.debug(e);
			forward = INPUT;
			setFeedBackMesssage(new VMessage(VMessage.ERROR, "登录失败", "请认真检查登录信息是否正确。"));
			setFieldErrorMessage("userNameError", "用户名或密码不正确");
		} catch (UserForbidException e) {
			logger.debug(e);
			forward = SUCCESS;
			setUserToSession((User) e.getPo(), true);
			setFeedBackMesssage(new VMessage(VMessage.SUCCESS, "登录成功", "您现在以 “" + pUser.getUserName() + "” 的身份登录超级土豆平台，祝您使用愉快！"));
		} catch (VerifyCodeException e) {
			logger.debug(e);
			forward = INPUT;
			setFeedBackMesssage(new VMessage(VMessage.ERROR, "登录失败", "请认真检查登录信息是否正确。"));
			setFieldErrorMessage("codeError", "验证码错误");
		}

		return forward;
	}

	public String logout() {
		getSession().removeAttribute("userInfo");
		return SUCCESS;
	}

	public String checkUserJson() {
		try {
			if (getUser().getType() == 1) {
				getUserService().isExist(getUser().getParentUserName());
			} else {
				getUserService().isExist(getUser().getUserName());
			}
			setJsonMessage(new VMessage(VMessage.SUCCESS, null, "该用户名可以使用"));
		} catch (UserExistException e) {
			logger.debug(e);
			setJsonMessage(new VMessage(VMessage.ERROR, null, "该用户名已经被注册"));
		}
		return SUCCESS;
	}

	private void setUserToSession(User pUser)  {
		this.setUserToSession(pUser, false);
	}
	
	private void setUserToSession(User pUser, boolean forbid)   {
		
		String sProperties = "userId, userName, lastLoginTime, lastLoginIP, modifyStatusTime,  money, publishPoint, publishPointReward, integral, integral, warning, userPopedoms, userPopedoms, ownTasks, ownTasks, ownTasks, ownTasks, othersTasks, othersTasks, othersTasks";
		String tProperties = "userId, userName, lastLoginTime, lastLoginIP, endForbidDateTime, money, publishPoint, publishPointReward, integral, levelImg, warning, vip,          vipEndTime,   task1,    task3,    task5,    task7,    task2,       task4,       task6";
		Properties properties = new Properties(sProperties, tProperties);

		VUser user = new VUser();
		user.setForbid(forbid);
		BeanUtils.copyBean(pUser, user, properties);

		getSession().removeAttribute("userInfo");
		getSession().setAttribute("userInfo", user);
	}

	public void validateRegister() {
		if (getUser() == null) {
			setFeedBackMesssage(new VMessage(VMessage.ERROR, "注册失败", "请认真检查注册信息是否正确。"));
			return;
		}
		CheckChain cc = new CheckNull(new CheckLength(6, 15, new CheckFormat(CheckFormat.USERNAME, null, "用户名只能使用a-z, A-Z, _, 0-9"), "用户名的长度为6-15个字符"), "用户名不能为空");
		setFieldErrorMessage("userNameError", cc.check(getUser().getUserName()));

		cc = new CheckNull(new CheckLength(6, 15, new CheckFormat(CheckFormat.PASSWORD, null, "密码只能使用a-z, A-Z, 0-9"), "密码的长度为6-15个字符"), "密码不能为空");
		setFieldErrorMessage("passwordError", cc.check(getUser().getPassword()));

		cc = new CheckNull(new CheckLength(6, 15, new CheckFormat(CheckFormat.PASSWORD, new CheckEquals(getUser().getPassword(), getUser().getPassword2(), null, "两次输入的密码不同"), "密码只能使用a-z, A-Z, 0-9"), "密码的长度为6-15个字符"), "密码不能为空");
		setFieldErrorMessage("password2Error", cc.check(getUser().getPassword2()));

		cc = new CheckNull(new CheckLength(6, 6, new CheckFormat(CheckFormat.OPERATE_CODE, null, "操作码只能使用0-9"), "操作码的长度为6个数字"), "操作码不能为空");
		setFieldErrorMessage("operateCodeError", cc.check(getUser().getOperateCode()));

		cc = new CheckNull(new CheckLength(6, 6, new CheckFormat(CheckFormat.OPERATE_CODE, new CheckEquals(getUser().getOperateCode(), getUser().getOperateCode2(), null, "两次输入的操作码不同"), "操作只能使用0-9"), "操作码的长度为6个字符"), "操作码不能为空");
		setFieldErrorMessage("operateCode2Error", cc.check(getUser().getOperateCode2()));

		cc = new CheckNull(new CheckFormat(CheckFormat.TAOBAO_URL, null, "店铺地址格式不正确"), "店铺地址不能为空");
		setFieldErrorMessage("tbUrlError", cc.check(getUser().getTbUrl()));

		cc = new CheckNull(null, "掌柜名称不能为空");
		setFieldErrorMessage("shopKeeperError", cc.check(getUser().getShopKeeper()));

		cc = new CheckNull(new CheckLength(5, 15, new CheckFormat(CheckFormat.QQ, null, "QQ只能使用0-9"), "QQ的长度为5-15个数字"), "QQ不能为空");
		setFieldErrorMessage("qqError", cc.check(getUser().getOperateCode()));

		cc = new CheckNull(new CheckLength(5, 5, new CheckFormat(CheckFormat.CODE, null, "验证码只能使用a-z, A-Z, 0-9"), "验证码的长度为5个字符"), "验证码不能为空");
		setFieldErrorMessage("codeError", cc.check(getUser().getCode()));

		cc = new CheckNoNull(new CheckLength(6, 15, new CheckFormat(CheckFormat.USERNAME, null, "推荐人只能使用a-z, A-Z, _, 0-9"), "推荐人的长度为6-15个字符"), "");
		setFieldErrorMessage("parentUserNameError", cc.check(getUser().getParentUserName()));
	}

	public void validateLogin() {
		if (getUser() == null) {
			setFeedBackMesssage(new VMessage(VMessage.ERROR, "登录失败", "请认真检查登录信息是否正确。"));
			return;
		}
		CheckChain cc = new CheckNull(new CheckLength(6, 15, new CheckFormat(CheckFormat.USERNAME, null, "用户名不正确"), "用户名不正确"), "用户名不能为空");
		setFieldErrorMessage("userNameError", cc.check(getUser().getUserName()));

		cc = new CheckNull(new CheckLength(6, 15, new CheckFormat(CheckFormat.PASSWORD, null, "密码不正确"), "密码不正确"), "密码不能为空");
		setFieldErrorMessage("passwordError", cc.check(getUser().getPassword()));

		cc = new CheckNull(new CheckLength(5, 5, new CheckFormat(CheckFormat.CODE, null, "验证码不正确"), "验证码不正确"), "验证码不能为空");
		setFieldErrorMessage("codeError", cc.check(getUser().getCode()));
	}
}
